from django.contrib.auth.decorators import login_required
from django.http import JsonResponse, HttpResponseRedirect

from two_comment.models import Comment, CommentReply
from users.models import User
from .forms import CommentForm, CommentReplyForm
from recommendation.models import Resume
from . import signals


@login_required
def submit_comment(request, pk):
    if pk:
        try:
            entry = Resume.objects.get(id=pk)
            form = CommentForm(data=request.POST)
            if form.is_valid():
                new_comment = form.save(commit=False)
                new_comment.entry = entry
                new_comment.author = request.user
                new_comment.save()
                return HttpResponseRedirect(entry.get_absolute_url())
            else:
                return HttpResponseRedirect('/')
        except Resume.DoesNotExist:
            return JsonResponse({'status': 'ko'})



@login_required
def submit_reply(request, pk):
    # 要回复的评论id
    commnet_id = request.POST.get('commnet_id')
    # 被回复者id
    reply_to_id = request.POST.get('reply_to_id')
    content = request.POST.get('content')
    if commnet_id and reply_to_id:
        try:
            comment = Comment.objects.get(id=commnet_id)
            reply_to = User.objects.get(id=reply_to_id)

            new_reply = CommentReply()
            new_reply.comment = comment
            new_reply.reply_from = request.user
            new_reply.reply_to = reply_to
            new_reply.content = content
            new_reply.save()
            return JsonResponse({'status': 'ok'})

        except User.DoesNotExist or CommentReplyForm.DoesNotExist:
            return JsonResponse({'status': 'no match '})
    return JsonResponse({'status': 'id error '})
